interface State {
  timeout: NodeJS.Timeout | null;
  canExecute: boolean;
}
const state: State = {
  timeout: null,
  canExecute: false,
};
const bg_url = import.meta.env.VITE_BASE_URL;
import { https } from "@/api/api";
import { useUserStore } from "@/store";
// 添加cdn域名前缀
export const cdn = (url: string = "") => {
  if (!url) return "";
  if (url.indexOf("http") === 0) {
    return url;
  }
  const cdnurl = import.meta.env.VITE_BASE_URL;
  return cdnurl + url;
};

// 复制
export function copyText(text: string) {
  // #ifndef H5
  uni.setClipboardData({
    data: text,
    success: function () {
      showToast("复制成功!");
    },
    fail: function () {
      showToast("复制失败!");
    },
  });
  // #endif
  // #ifdef H5
  const inputo = document.createElement("textarea");
  document.body.appendChild(inputo);
  inputo.value = text;
  inputo.setAttribute("readOnly", "readOnly");
  inputo.select();
  document.execCommand("Copy");
  document.body.removeChild(inputo);
  showToast("复制成功", 2000);
  // #endif
}
// 默认提示
export const showToast = (title = "访问失败！", duration: number = 2000) => {
  uni.showToast({
    title: title,
    icon: "none",
    duration: duration,
    mask: true,
  });
};
// 跳转方式
export const navigateTo = (url: string, way: number = 10) => {
  // tabbar 跳转方式
  if (way === 0) {
    uni.switchTab({
      url: url,
    });
  }
  // reLaunch 关闭所有页面
  if (way === 1) {
    uni.reLaunch({
      url: url,
    });
  }
  // redirectTo 关闭当前页面
  if (way === 2) {
    uni.redirectTo({
      url: url,
    });
  }
  // 跳转非tabbar 页面
  if (way === 10) {
    uni.navigateTo({
      url: url,
    });
  }
};

// -防抖
export function debounce(
  func: Function,
  times: number = 500,
  immediate: boolean = false
) {
  // let timeout = null
  // 清除定时器
  if (state.timeout !== null) clearTimeout(state.timeout);
  // 立即执行，传true 则不进行防抖 一般不传递第三个参数
  if (immediate) {
    var callNow = !state.timeout;
    state.timeout = setTimeout(function () {
      state.timeout = null;
    }, times);

    if (callNow) typeof func === "function" && func();
  } else {
    // 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时times毫秒后执行func回调方法
    state.timeout = setTimeout(function () {
      typeof func === "function" && func();
    }, times);
  }
}

// -节流
export function throttle(func: Function, times: number = 500) {
  if (state.canExecute) {
    state.canExecute = false;
    // 执行你的函数逻辑
    func();
    setTimeout(() => {
      state.canExecute = true;
    }, times); // 设置节流的时间间隔，单位为毫秒
  }
}
// -是否是 管理者
export const authAdmin = () => {
  const userInfo = useUserStore();
  return userInfo.info?.type === 3;
};
// -是否是业务经理
export const authManage = () => {
  const userInfo = useUserStore();
  return userInfo.info?.type === 2;
};
// -是否为普通员工
export const authStaff = () => {
  const userInfo = useUserStore();
  return userInfo.info?.type === 1;
};
// -图片上传
// file 上传图片
export const upload = (file: Files, apiName: string) => {
  return new Promise((reslove) => {
    if (!file?.size && file.url.split("://")[0] === "https") {
      reslove({
        file: file.url.split("marker/")[1],
      });
      return;
    }
    uni.uploadFile({
      url: bg_url + `api/${apiName}?id=${uni.getStorageSync("userData")?.id}`,
      filePath: file.url,
      name: "file",
      header: {
        Accept: "text/json",
      },
      success: (res) => {
        const data = JSON.parse(res.data);
        if (data.data.id) {
          // 更换 id
          uni.setStorageSync("userData", {
            ...uni.getStorageSync("userData"),
            id: data.data.id,
          });
        }
        reslove(data.data);
      },
      fail: (error) => {
        showToast(error.errMsg);
        reslove({
          code: -1,
          data: {
            msg: "=====------",
            file: null,
          },
          file: null
        });
      },
    });
  });
};
// 登录
export const login = async (callback: Function): Promise<UserInfo> => {
  return new Promise((reslove) => {
    uni.login({
      success: async ({ code }: { code: string }) => {
        const res = await https({
          mode: "login",
          name: "apiWechatLogin",
          data: {
            code: code,
          },
        });
        if (res?.code !== 0) return showToast(res.data.msg || "");
        reslove(res.data);
        // // 存储本地
        // uni.setStorageSync("userData", res.data);
      },
      fail: ({ errMsg }: { errMsg: string }) => {
        showToast(errMsg);
      },
    });
  });
};

// 未进行授权
export const unauthorized = () => {
  uni.getSetting({
    success: (res) => {
      let authSetting = res.authSetting
      if (authSetting['scope.userLocation']) {
        // 已授权
      } else {
        uni.showModal({
          title: '您未开启地理位置授权',
          content: '是否开启授权，方便标记您需要的点',
          success: res => {
            if (res.confirm) {
              uni.openSetting()
            }
          }
        })
      }
    }
  })
}
// 获取用户当前位置信息
export const currentLocation = (): Promise<{ lng: string, lat: string } | false> => {
  return new Promise((resolve, reject) => {
    let _locationChangeFn = (e: LngLat) => {
      resolve({
        lng: e.longitude + '',
        lat: e.latitude + '',
      });
      uni.offLocationChange(_locationChangeFn)
    }
    uni.startLocationUpdate({
      success: (e) => {
        uni.onLocationChange(_locationChangeFn);
      },
      fail: (err) => {
        unauthorized()
        resolve(false)
        reject()
      }
    })
  })
}
// 处理时间戳
export const timeFormat = (dateTime: number | null, fmt = "yyyy/mm/dd") => {
  // 如果为null,则格式化当前时间
  if (!dateTime) dateTime = Number(new Date());
  // 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
  if (dateTime.toString().length == 10) dateTime *= 1000;
  let date = new Date(dateTime);
  let ret;
  let opt: any = {
    "y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "h+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "s+": date.getSeconds().toString(), // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
      );
    }
  }
  return fmt;
};